from django.shortcuts import render
from post.models import Post
from django.core.paginator import Paginator
import math
from markdown import markdown

def index(request, page_id=1):
    num = int(page_id)
    # 获取所有帖子的信息
    postList = Post.objects.all().order_by('-create')
    # 创建分页器对象
    pageObj = Paginator(postList, 1)
    # 获取当前页的数据
    perPageList = pageObj.page(num)

    # 生成页码数列表
    # 每页开始页码
    begin = (num-int(math.ceil(10.0 / 2)))
    if begin < 1:
        begin = 1
    # 每页结束页码
    end = begin + 9
    if end > pageObj.num_pages:
        end = pageObj.num_pages
    if end <= 10:
        begin = 1
    else:
        begin = end - 9
    pageList = range(begin, end+1)

    return render(request, 'index.html', {'postList': perPageList, 'pageList': pageList, 'currentPage': num})

# 查看阅读全文
def detail(request, post_id):
    post_id = int(post_id)
    post = Post.objects.get(pid=post_id)
    return render(request, 'detail.html', {'post': post})

# 根据cid类别查询所有帖子
def queryPostByCid(request, category_id):
    postList = Post.objects.filter(pcategory_id = category_id)
    return render(request, 'article.html', {'postList': postList})

# 根据发帖时间查询所有帖子
def queryPostByCreate(request, archieve_year, archieve_month):
    postList = Post.objects.filter(create__year=archieve_year, create__month=archieve_month)
    return render(request, 'article.html', {'postList': postList})